package com.pjb.springbootjjwt.store.storage.csv;

import com.pjb.springbootjjwt.store.entity.Line;
import com.pjb.springbootjjwt.store.storage.DDL;
import com.pjb.springbootjjwt.store.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.pjb.springbootjjwt.store.utils.RandomAccessFileUtil.sp;

public class PoiUtil {

    public static void delete(String table, int lineNo) throws IOException {
        String c = FileUtil.read(table + ".csv");
        String[] arr = c.split(sp);
        List<String> list = new ArrayList<>(Arrays.asList(arr));
        list.remove(lineNo);
        String r = StringUtils.join(list, sp) + sp;
        FileUtil.write(FileUtil.getPath(table + ".csv"), r);
    }

    public static String read(String table) throws IOException {
        File file = new File(FileUtil.DIR + FileUtil.getPath(table + ".csv"));
        BufferedReader br = new BufferedReader(new FileReader(file));
        String strLine = "";

        String c = "";
        while ((strLine = br.readLine()) != null) {
            c += strLine + ";\r\n";
        }
        return c;
    }

    public static Line toLine(String lineStr) {
        if (StringUtils.isEmpty(lineStr) || lineStr.trim().isEmpty()) return null;

        lineStr = lineStr.replaceFirst(",", ":");
        String[] array = lineStr.split(":");
        Line line = new Line();
        line.setKey(array[0].trim());
        String dataStr = line.getKey() + "," + array[1];
        line.setData(Arrays.asList(dataStr.split(",")));
        return line;
    }

    public static String toText(Line line) {
        String c = StringUtils.join(line.getData(), ",");
        return c;
    }

    public static void main(String[] args) throws Exception {
        new DDL().use("test");
        String c = read("csv_test");
        String[] arr = c.split(";\r\n");
        for (String a : arr) {
            Line line = toLine(a);
            System.out.println(line);
            String text = toText(line);
            System.out.println(text);
        }
        System.out.println(1);
        delete("csv_test", 4);
    }
}
